package com.leetcode.partition11;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

/**
 * @author `RKC`
 * @date 2022/2/12 17:58
 */
public class LC1020飞地的数量_并查集 {

    private static final int N = 250010;
    private static final int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    private static int[] parent = new int[N];
    private static Set<Integer> set = new HashSet<>(N);
    private static int n = 0, m = 0;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        int n = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
        int[][] grid = new int[n][m];
        for (int i = 0; i < n; i++) {
            ss = reader.readLine().split(" ");
            for (int j = 0; j < m; j++) grid[i][j] = Integer.parseInt(ss[j]);
        }
        writer.write(numEnclaves(grid) + "\n");
        writer.flush();
    }

    public static int numEnclaves(int[][] grid) {
        n = grid.length;
        m = grid[0].length;
        for (int i = 1; i < N; i++) parent[i] = i;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1) {
                    for (int[] dir : dirs) {
                        int x = i + dir[0], y = j + dir[1];
                        if (x < 0 || x >= n || y < 0 || y >= m || grid[x][y] == 0) continue;
                        int idx1 = get(i, j), idx2 = get(x, y);
                        int p1 = find(idx1), p2 = find(idx2);
                        if (p1 != p2) parent[p1] = p2;
                    }
                }
            }
        }
        //找出所有边界的连通块编号
        for (int i = 0; i < n; i++) {
            if (grid[i][0] == 1) set.add(find(get(i, 0)));
            if (grid[i][m - 1] == 1) set.add(find(get(i, m - 1)));
        }
        for (int j = 0; j < m; j++) {
            if (grid[0][j] == 1) set.add(find(get(0, j)));
            if (grid[n - 1][j] == 1) set.add(find(get(n - 1, j)));
        }
        int ans = 0;
        for (int i = 1; i < n - 1; i++) {
            for (int j = 1; j < m - 1; j++) {
                if (grid[i][j] == 1 && !set.contains(find(get(i, j)))) {
                    ans++;
                }
            }
        }
        return ans;
    }

    private static int get(int x, int y) {
        return x * m + y;
    }

    private static int find(int x) {
        if (x != parent[x]) parent[x] = find(parent[x]);
        return parent[x];
    }
}
